﻿using System;
using System.ComponentModel;
using System.Drawing;
using System.IO;
using System.Windows.Forms;

namespace ImageFan.Controls
{
    internal partial class FolderTreeView
        : TreeView
    {
        public FolderTreeView()
        {
            InitializeComponent();
        }

        public string Folder
        {
            get
            {
                return (SelectedNode == null ? null : (string)SelectedNode.Tag);
            }
            set
            {
                if (value != null)
                {
                    Nodes.Clear();

                    try
                    {
                        var dirInfo = new DirectoryInfo(value);
                        dirInfo.GetDirectories();

                        var folderNode = new TreeNode(value);
                        folderNode.Tag = value;
                        if (FolderIsDriveRoot(value))
                        {
                            folderNode.ImageIndex = 0;
                            folderNode.SelectedImageIndex = 0;
                        }
                        Nodes.Add(folderNode);

                        BuildSubfoldersList(folderNode, value);

                        folderNode.Expand();
                    }
                    catch
                    {
                    }
                }
            }
        }


        #region Protected

        protected override void OnMouseEnter(EventArgs args)
        {
            base.OnMouseEnter(args);

            if (!Focused)
                Focus();
        }

        protected override void OnAfterSelect(TreeViewEventArgs args)
        {
            base.OnAfterSelect(args);

            args.Node.Nodes.Clear();
            BuildSubfoldersList(args.Node, (string)args.Node.Tag);
        }

        #endregion


        #region Private

        private void BuildSubfoldersList(TreeNode currentNode, string folderToView)
        {
            try
            {
                var dirInfo = new DirectoryInfo(folderToView);
                var subDirs = dirInfo.GetDirectories();

                Array.Sort(subDirs,
                           (subDir1, subDir2) => subDir1.Name.CompareTo(subDir2.Name));

                foreach (var aSubDir in subDirs)
                {
                    try
                    {
                        var newFolderNode = new TreeNode(aSubDir.Name);
                        newFolderNode.Tag = aSubDir.FullName;
                        currentNode.Nodes.Add(newFolderNode);
                    }
                    catch
                    {
                    }
                }
            }
            catch
            {
            }
        }

        private bool FolderIsDriveRoot(string folder)
        {
            return (folder.LastIndexOf(Path.DirectorySeparatorChar) == 2);
        }

        #endregion
    }
}
